<?php
/**
 * Created by PhpStorm.
 * User: ybjaa
 * Date: 2017/5/25
 * Time: 9:53
 */

namespace App\Business\File;


use App\Business\BusBase;
use App\Business\ReturnResult;
use App\Models\files;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

abstract class FileBase extends BusBase
{



    private function getSuffix($fileName){

        $name="";
        if($fileName) $name=trim($fileName);

        if($name==="") return "";
        return strtolower(substr($name,strrpos($name,'.')+1));

    }


    /**
     * @param $path
     * @return ReturnResult
     */
    protected function saveFile($path){


        $requestFile=request()->file('qqfile');

        $fileName=$requestFile->getClientOriginalName();

        //手动更改一些奇怪的后缀

        $suffix=$this->getSuffix($fileName);

        $newPath="";


        $size=$requestFile->getClientSize();
        $mimeType=$requestFile->getClientMimeType();

        switch ($suffix)
        {

           /* case "xlsx":
                $newPath= $requestFile->storeAs($path,Str::random(40).'.'.$suffix);
                break;*/

            case "":
            case null:
            $newPath= $requestFile->store($path);
            break;


            default:
                //$newPath= request()->file('qqfile')->storeAs($path,Str::random(40).'.'.$suffix);
                $newPath= $requestFile->storeAs($path,Str::random(40).'.'.$suffix);
                break;

        }




        $isExist= Storage::disk("local")->exists($newPath);

        if(!$isExist)
            return ReturnResult::Error(null,"文件上传失败");


        $urlPath=Storage::disk("local")->url($newPath);
        //写文件

        $file=new files();
        $file->fileName=$fileName;
        $file->userID=$this->getUserID();
        $file->suffix=$this->getSuffix($newPath);
        $file->filePath=$newPath;
        $file->fileUrlPath=$urlPath;
        $file->mimeType=$mimeType;
        $file->size=$size;

        $file->save();


        return ReturnResult::Success($file);

    }




}